<script setup lang='ts'>
import { useUserStore } from '../../store/modules/user';
import { User, Lock } from '@element-plus/icons-vue';
import { reactive, ref } from 'vue';
import { ElNotification } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { getTimes } from '../../utils/time.ts';
import { loginFormData, registerFormData } from '@/api/user/type';
import { reqRegister } from '../../api/user/index';

const userStore = useUserStore();
const $router = useRouter();
const $route = useRoute();

let loginUser: loginFormData = reactive({
  username: "admin",
  password: "111111"
});

let registerUser: registerFormData = reactive({
  username: "admin",
  password: "111111",
  confirmPassword: "111111"
});

const loading = ref(false);
const isRegisterMode = ref(false);

const loginForms = ref();
const registerForms = ref();

const login = async () => {
  await loginForms.value.validate();
  loading.value = true;
  try {
    await userStore.userLogin(loginUser);
    let redirect: any = $route.query.redirect;
    $router.push({ path: redirect || "/" });
    ElNotification({
      type: 'success',
      message: `HI,${getTimes()}好`
    });
    loading.value = false;
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message
    });
    loading.value = false;
  }
};

const register = async () => {
  await registerForms.value.validate();
  loading.value = true;
  try {
    if (registerUser.password !== registerUser.confirmPassword) {
      throw new Error("两次输入的密码不一致");
    }
    await reqRegister(registerUser);
    ElNotification({
      type: 'success',
      message: "注册成功，请登录"
    });
    isRegisterMode.value = false;
    loading.value = false;
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message
    });
    loading.value = false;
  }
};

const validatorUserName = (rule: any, value: any, callback: any) => {
  if (value.length >= 5) {
    callback();
  } else {
    callback(new Error('账号长度至少五位'));
  }
};

const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.length >= 6) {
    callback();
  } else {
    callback(new Error('密码长度至少六位'));
  }
};

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerUser.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const rules = {
  username: [{ trigger: 'change', validator: validatorUserName }],
  password: [{ trigger: 'change', validator: validatorPassword }]
};

const registerRules = {
  username: [{ trigger: 'change', validator: validatorUserName }],
  password: [{ trigger: 'change', validator: validatorPassword }],
  confirmPassword: [{ trigger: 'change', validator: validateConfirmPassword }]
};
</script>

<template>
  <div class="log_container">
    <el-row :gutter="20">
      <el-col :span="12" :offset="0" :xs="0"></el-col>
      <el-col :span="12" :offset="0">
        <el-form v-if="!isRegisterMode" class="login_form" :model="loginUser" :rules="rules" ref="loginForms">
          <h1>Hello</h1>
          <h2>欢迎</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginUser.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" show-password v-model="loginUser.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="log_btn" :loading="loading" type="primary" size="default" @click="login">登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="text" @click="isRegisterMode = true">还没有账号？去注册</el-button>
          </el-form-item>
        </el-form>

        <el-form v-else class="login_form" :model="registerUser" :rules="registerRules" ref="registerForms">
          <h1>注册</h1>
          <h2>欢迎加入我们</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="registerUser.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" show-password v-model="registerUser.password"></el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input type="password" :prefix-icon="Lock" show-password v-model="registerUser.confirmPassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="log_btn" :loading="loading" type="primary" size="default" @click="register">注册</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="text" @click="isRegisterMode = false">已有账号？去登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
/* 设置 .log_container 元素占满整个窗口 */
.log_container {
  width: 100%;
  height: 100vh;
  background-size: cover;
  background: url('@/assets/images/background.jpg') no-repeat;

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url("@/assets/images/login_form.png") no-repeat;
    background-size: cover;
    border-radius: 10px;
    padding: 40px;
  }

  h1 {
    font-size: 40px;
    color: #fdfdfd;
  }

  h2 {
    font-size: 20px;
    color: #fdfdfd;
    margin: 20px 20px;
  }

  .log_btn {
    width: 100%;
  }
}
</style>